package org.jef.socket.thread;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version 1.0
 * @description: 单例线程池
 * @author: ChengZhi 0336
 * @create: 2024-09-13 17:44
 **/
public class SingletonThreadPool {

    /**
     * 记录比赛和倒计时线程的关系
     */
    private static final Map<String, ExecutorService> pools = new ConcurrentHashMap<>();

    /**
     * 记录任务和比赛的映射关系
     */
    private static final Map<String, Funcable> tasks = new ConcurrentHashMap<>();

    /**
     * 开始计时
     * @param key
     * @param task
     */
    public static void executeTask(String key, Runnable task) {
        ExecutorService executorService = pools.get(key);
        if (executorService == null) {
            executorService = Executors.newSingleThreadExecutor();
            pools.put(key, executorService);
            tasks.put(key, (Funcable) task);
            executorService.execute(task);
            return;
        }
        executorService.execute(task);
    }

    /**
     * 销毁线程
     * @param key
     * @return
     */
    public static Object shutdown(String key, boolean isReset) {
        ExecutorService executorService = pools.get(key);
        if (executorService != null) {
            // 停止线程池之前获取线程当前执行到的值
            Funcable funcable = tasks.get(key);
            // 停止线程
            funcable.stop();
            // 记录当前剩余时间到数据库
            if (!isReset) {
                funcable.execute();
            } else {
                funcable.reset();
            }
            Object lastValue = funcable.getLastValue();
            executorService.shutdown();
            pools.remove(key);
            tasks.remove(key);
            return lastValue;
        }
        return null;
    }
}
